<?php

namespace app\api\model;

use app\api\service\Uploader;
use think\Db;
use think\Model;

class MediaFiles extends Model
{
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    protected $name = "jq_media_files";

    public function info()
    {
        return $this->hasOne('base_category', 'second_cateid')->setEagerlyType(0);
    }

    function getList($media_id = 0, $type = 0, $media_type = 0)
    {
        $data = request()->post();
        $listRows = $data['listRows'] ?? 10;
        $page = $data['page'] ?? 1;

        $map = [];
        $map['is_deleted'] = '0';

        // 单个素材
        if ($media_id > 0) {
            $map['media_id'] = $media_id;
        }

        $order = 'sort asc,create_time desc';

        // 素材类型
        if ($media_type > 0) {
            $order = 'create_time desc';
            if (isset($data['status']) && $data['status']) {
                $str = 'status';
                if ($media_type == 2) {
                    $str = "compress_status";
                }
                $map[$str] = $data['status'];
            }
        }

        $map['status'] = '1';


        $model = $this;


//        if ($type == 1) {
//            $model->field('cover_image,download_num,file_size,title,file_path,compress_file_path');
//        }
        $file_list = $model
            ->where($map)
            ->order($order)
            ->paginate($listRows, false, [
                'page' => $page
            ])->toArray();

        $file_list = $this->handleData($file_list);
        return $file_list;
    }


    /**
     * 获取上传进程
     * @author 01
     * @email 319204520@qq.com
     * @date 2023-02-19 17:52
     */
    public function getUploadList()
    {
        $data = request()->post();
        $listRows = $data['listRows'] ?? 10;
        $page = $data['page'] ?? 1;

        $map = [];
        $map['is_deleted'] = '0';

        // 上传中 上传失败 上传成功排序
        $order = "field(status,'0','2','1'),create_time desc";
        if (isset($data['status']) && ($data['status'] || $data['status'] == '0')) {
            $map['status'] = $data['status'];
        }

        $file_list = $this->where($map)
            ->orderRaw($order)
            ->field('id,type,title,file_name,file_type,file_path,file_size,cover_image,compress_file_path,status,upload_progress as progress')
            ->paginate($listRows, false, [
                'page' => $page
            ])->toArray();

        $file_list = $this->handleData($file_list);
        return $file_list;
    }


    /**
     * 获取上传进程
     * @author 01
     * @email 319204520@qq.com
     * @date 2023-02-19 17:52
     */
    public function getCompressList()
    {
        $data = request()->post();
        $listRows = $data['listRows'] ?? 10;
        $page = $data['page'] ?? 1;

        $map = [];
        $map['is_deleted'] = '0';
        $map['status'] = '1';
        // 上传中 上传失败 上传成功排序
        $order = "field(compress_status,'0','2','1'),update_time desc";
        if (isset($data['status']) && ($data['status']|| $data['status'] == '0')) {
            $map['compress_status'] = $data['status'];
        }
        $file_list = $this->where($map)
            ->orderRaw($order)
            ->field('id,type,title,file_name,file_type,file_path,file_size,cover_image,compress_file_path,compress_status as status,compress_progress as progress')
            ->paginate($listRows, false, [
                'page' => $page
            ])->toArray();

        $file_list = $this->handleData($file_list);
        return $file_list;
    }

    function handleData($list)
    {
        foreach ($list['data'] as &$item) {
            $item['cover_image'] = cdnurl($item['cover_image']);
            $item['file_path'] = cdnurl($item['file_path']);
            $item['compress_file_path'] = cdnurl($item['compress_file_path']);
            $item['file_size'] = (new Uploader())->getFilesize($item['file_size'] ?? 0);
//            if ($item['type'] == '0') {
//                $item['cover_image'] = $item['cover_image'] ? $item['cover_image'] : $item['file_path'];
//            }
        }

        return $list;
    }

    /**
     * 获取视频总下载次数
     * @author 01
     * @email 319204520@qq.com
     * @date 2023-02-19 16:38
     */
    function getMediaDownloadNum(int $media_id = 0)
    {
        $map = [
            'media_id'   => $media_id,
            'is_deleted' => '0'
        ];
        $download_num = $this->where($map)
            ->sum('download_num');


        return $download_num ?? 0;
    }

    /**
     * 获取媒咨封面
     * @author 01
     * @email 319204520@qq.com
     * @date 2023-02-19 16:40
     */
    public function getMediaCoverImage($media_id = 0)
    {
        $map = [
            'media_id'    => $media_id,
            'cover_image' => [
                'exp',
                Db::raw("IS NOT NULL")
            ],
            'is_deleted'  => '0'
        ];
        $first = $this->where($map)
            ->order('sort asc,create_time asc')
            ->find();

        $cover_image = "";
        if ($first) $cover_image = cdnurl($first['cover_image']);
        return $cover_image;
    }


    /**
     * 获取文件数量
     * @author 01
     * @email 319204520@qq.com
     * @date 2023-02-19 17:17
     */
    function getFileNum(int $media_id = 0)
    {
        $map = [
            'media_id'   => $media_id,
            'is_deleted' => '0',
            'status'    => '1'
        ];
        $download_num = $this->where($map)
            ->count();

        return $download_num ?? 0;
    }


    public function getFileInfo(int $media_id = 0)
    {
        $map = [
            'media_id'   => $media_id,
            'is_deleted' => '0',
            'file_info'  => [
                'exp',
                Db::raw("IS NOT NULL")
            ]
        ];

        $fileInfo = $this->where($map)
            ->order('sort asc,create_time asc')
            ->find();

        return $fileInfo['file_info'] ?? '';
    }


    // 删除本地文件
    function del_dev_file($media_ids = "", $file_ids = "")
    {
        $map = [];
//        $map['is_deleted'] = '0';

        if ($media_ids) {
            $map['media_id'] = ['in', $media_ids];
        }

        if ($file_ids) {
            $map['id'] = ['in', $file_ids];
        }

        $list = $this->where($map)->select();
        // 删除本地文件
        foreach ($list as $item) {
            // 校验
            if ($item['file_path'] && !$this->get([
                    'is_deleted' => '0',
                    'file_path'  => $item['file_path']
                ])) {
                @unlink('public' . $item['file_path']);
                $item['compress_file_path'] && @unlink('public' . $item['compress_file_path']);
            }
        }
    }

}
